package com.bp.hearthealth.pulse.lnapps.ads.admob.rewarded_ad

import android.app.Activity
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsCount
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.timer.TimerObserver
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback


object AdMobRewardedAdManager : TimerObserver {

    private var adListener: AdMobRewardedAdListener? = null
    private var rewardedAd: RewardedAd? = null
    private var numberRetries = 0//重试次数
    private var adUnitId = ""
    var loading = true

    fun setRewardedAdListener(listener: AdMobRewardedAdListener?) {
        adListener = listener
    }

    // 加载激励广告
    fun loadRewardedAd(adUnitId: String) {
        if (!AdsSwitch.getBoolean(AdsSwitch.adRVControl)) {
            adListener?.onNotReady()
            return
        }
        AdMobRewardedAdManager.adUnitId = adUnitId
        val adRequest = AdRequest.Builder().build()
        RewardedAd.load(BpApplication.context,
            adUnitId,
            adRequest,
            object : RewardedAdLoadCallback() {
                override fun onAdFailedToLoad(adError: LoadAdError) {
                    loading = false
                    LogUtil.i("激励广告加载失败: $adError")
                    if (numberRetries < 3) {
                        loadRewardedAd(adUnitId)
                    }
                    adListener?.onAdFailedToLoad()
                    numberRetries++
                    rewardedAd = null
                }

                override fun onAdLoaded(ad: RewardedAd) {
                    LogUtil.i("激励广告加载成功")
                    loading = false
                    rewardedAd = ad
                    adListener?.onAdLoaded(ad)
                    setupAdCallbacks()
                }
            })
    }

    // 设置广告回调
    private fun setupAdCallbacks() {
        rewardedAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
            override fun onAdClicked() {
                AdsCount.incrementClickCount()
                LogUtil.i("激励广告被点击")
                adListener?.onAdClicked()
            }

            override fun onAdDismissedFullScreenContent() {
                LogUtil.i("激励广告完全关闭")
                rewardedAd = null
                adListener?.onAdDismissedFullScreenContent()
//                loadRewardedAd(adUnitId)
            }

            override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                LogUtil.i("激励广告展示失败: $adError")
                adListener?.onAdFailedToShowFullScreenContent()
                rewardedAd = null
            }

            override fun onAdImpression() {
                LogUtil.i("激励广告印象被记录")
                adListener?.onAdImpression()
            }

            override fun onAdShowedFullScreenContent() {
                LogUtil.i("激励广告完全展示")
                AdsCount.incrementDisplayCount()
                adListener?.onAdShowedFullScreenContent()
            }
        }
    }

    // 展示广告
    fun showRewardedAd(activity: Activity) {
        if (!AdsSwitch.getBoolean(AdsSwitch.adRVControl)) {
            adListener?.onAdClosed()
            return
        }
        //失败已超过3次，并且最后一次已经加载完成
        if (numberRetries >= 2 && !loading) {
            LogUtil.i("激励广告加载失败已超过3次，需再次重试")
            numberRetries = 0
            loadRewardedAd(adUnitId)
            loading = true
        }
        rewardedAd?.let { ad ->
            ad.show(activity) { rewardItem ->
                val rewardAmount = rewardItem.amount
                val rewardType = rewardItem.type
                LogUtil.i(
                    "获取奖励：rewardType：$rewardType ----- rewardAmount：$rewardAmount"
                )
            }
        } ?: run {
            adListener?.onNotReady()
            LogUtil.i("激励广告尚未准备就绪")
        }
    }

    fun getRewardedAd(): RewardedAd? {
        return rewardedAd
    }

    //释放资源
    fun release() {
        rewardedAd?.fullScreenContentCallback = null
        rewardedAd = null
    }

    override fun clearCache() {
        LogUtil.i("观察者模式释放 激励广告资源")
        rewardedAd = null
        loadRewardedAd(adUnitId)
    }
}
